package com.baseproject.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.baseproject.BaseApplication;


/**
 * Created by hp on 2017/3/28.
 */

public class NetworkUtils {

    public static boolean showHintIfNetworkNotAvailable(Throwable e) {
        if (!NetworkUtils.isNetworkAvailable()) {
            ToastUtils.showSingleToast("请求失败，请检查网络!");
            LogUtils.logCatchedException(e, 2);
            return true;
        }
        return false;
    }

    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) BaseApplication.getApplication()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected() && info.getState() == NetworkInfo.State.CONNECTED)
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测当的网络（4G/3G/2G）状态
     * @param context context
     * @return boolean
     */
    public static boolean isGprsAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null)
            return false;
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
            return false;
        }
        NetworkInfo.State state = connectivityManager.getNetworkInfo(
                ConnectivityManager.TYPE_MOBILE).getState();
        return NetworkInfo.State.CONNECTED == state;
    }

    /**
     * 检测当的网络（WIFI）状态
     * @param context context
     * @return boolean
     */
    public static boolean isWifiAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null)
            return false;
        if (connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI) == null) {
            return false;
        }
        NetworkInfo.State state = connectivityManager.getNetworkInfo(
                ConnectivityManager.TYPE_WIFI).getState();
        return NetworkInfo.State.CONNECTED == state;
    }
}
